package logic

import (
	"apple/applerpc/applerpc"
	"apple/applerpc/internal/svc"
	"apple/cache"
	"apple/models/mysql"
	"context"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"time"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 分页
func (l *ListLogic) List(in *applerpc.ListRequest) (*applerpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	var user []mysql.User
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	result, _ := cache.Rdb.Get(l.ctx, "userlist").Result()
	if result == "" {
		mysql.DB.Debug().Limit(int(pageSize)).Offset(int(offset)).Order("password desc").Find(&user)
		marshal, _ := json.Marshal(&user)
		cache.Rdb.Set(l.ctx, "userlist", marshal, time.Hour*24).Result()
	} else {
		json.Unmarshal([]byte(result), &user)
	}

	var userlist []*applerpc.UserList
	for _, i2 := range user {
		list := applerpc.UserList{
			Account:  i2.Account,
			Password: i2.Password,
			Tel:      i2.Tel,
		}
		userlist = append(userlist, &list)
	}
	return &applerpc.ListResponse{
		List: userlist,
	}, nil
}
